package org.lw.springbootlw.common.advice;

import org.lw.springbootlw.common.exception.DepartmentNotFoundException;
import org.lw.springbootlw.common.response.ApiResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.NoSuchElementException;
/*
*   全局异常处理类: 用于处理所有Controller中抛出的异常
* */
@ControllerAdvice
public class GlobalExceptionHandler {


    // 处理找不到资源的异常
    @ExceptionHandler(NoSuchElementException.class)
    public ResponseEntity<ApiResponse<String>> handleNoSuchElementException(NoSuchElementException ex) {
        return ResponseEntity
                .status(404) // 404 Not Found
                .body(new ApiResponse<>(404, ex.getMessage(), null));
    }

    @ExceptionHandler(DepartmentNotFoundException.class)
    public ResponseEntity<ApiResponse<String>> handleDepartmentNotFoundException(DepartmentNotFoundException e) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(new ApiResponse<>(404, e.getMessage(), null));
    }
    @ExceptionHandler(BadCredentialsException.class)
    public ResponseEntity<ApiResponse<String>> handleBadCredentialsException(BadCredentialsException e) {
        return ResponseEntity.status(401).body(new ApiResponse<>(401, "用户名或密码错误", null));
    }
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<String>> handleException(Exception e) {
        e.printStackTrace(); // 打印异常栈
        return ResponseEntity.status(500).body(new ApiResponse<>(500, "服务器错误", null));
    }

}

